<?php

namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Customer;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Spatie\Permission\Models\Permission;

class PublicController extends Controller
{
    private Request $request;

    /**
     * PublicController constructor.
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }
    //图片验证码
    public function codeImage(){
        $ipAddress = request()->ip();
        MyLog::info("请求Ip".json_encode($ipAddress));

        return app('captcha')->create('default', true);
    }
/**
 * 获取真实IP地址
 */
private function getRealIpAddress()
{
    $ipKeys = [
        'HTTP_CF_CONNECTING_IP',     // Cloudflare
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_X_CLUSTER_CLIENT_IP',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ];

    foreach ($ipKeys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            $ip = $_SERVER[$key];
            if (strpos($ip, ',') !== false) {
                $ip = explode(',', $ip)[0];
            }
            $ip = trim($ip);
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }

    return request()->ip();
}
    public function login()
    {
        
           // 获取真实IP
    $ipAddress = $this->getRealIpAddress();
    $userAgent = request()->userAgent();
    
    MyLog::info("真实IP: " . $ipAddress);
    MyLog::info("User-Agent: " . $userAgent);
        $captcha = $this->request->post('captcha'); //验证码
        $key = $this->request->post('captchaKey'); //key
        MyLog::info("验证码".json_encode($captcha));
        MyLog::info("KEY值".json_encode($key));
        if (!captcha_api_check($captcha , $key)){
            return ResponseUtil::error( '验证码错误' );
        }
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $bool = Auth::guard('admin')->attempt([
            'username'=>$username,
            'password'=>$password
        ]);

        MyLog::info("用户名".json_encode($username));
        MyLog::info("密码".json_encode($password));
        if (!$bool){
            return ResponseUtil::error('账号或密码错误');
        }
        return ResponseUtil::success('登录成功');
    }

    public function logout(){
        Auth::guard('admin')->logout();
        return ResponseUtil::success('退出成功');
    }

    public function exportImage($dir,$ymd,$path){ //显示图片
        $fullPath = storage_path('app').'/'.$dir.'/'.$ymd.'/'.$path;
        return response()->stream(function () use ($fullPath) {
            echo file_get_contents($fullPath);
        }, 200, ['Content-Type' => 'image/jpeg']);
    }

    public function userInfo(){ //获取用户信息
        $isLogin = Auth::guard('admin')->check();
        if (!$isLogin){
            return ResponseUtil::error("登录过期,请重新登录");
        }

        $admin = Auth::guard('admin')->user();
        $adminId = $admin->id;
        if ($adminId==1){
            $admin['noAuthFlags'] = []; //不具有的权限
        } else {
            $admin = Admin::query()->with(['roles'=>function($role){
                $role->with(['permissions'=>function($permission){
                    $permission->select('id','name');
                }])->select('id');
            }])->select('id','username')->find($adminId);
            $authFlags = [];
            foreach($admin->roles as $role){
                foreach($role->permissions as $permission){
                    $authFlags[] = $permission->name;
                }
            }
            $allPermissions = Permission::all()->pluck('name')->toArray();
            $noAuthFlags = array_values(array_diff($allPermissions , $authFlags));
            $admin['noAuthFlags'] = $noAuthFlags; //不具有的权限
        }
        return ResponseUtil::success( $admin );
    }

   /* public function laravelAuthenticate(){ //test
        $request = request();
        $credentials = $request->only('email', 'password');

        Auth::guard('admin')->login();

        if (Auth::guard('admin')->attempt($credentials)) {

            $request->session()->regenerate();

            return redirect()->intended('dashboard');
        }

        return ResponseUtil::error();

    }*/

    public function resetPass(){

        $customers = Customer::query()->get();

        foreach($customers as $customer){
            $customer->password =  Crypt::encryptString($customer->password);
            $customer->save();
        }
        echo 1;

    }

}
